const jwt = require('jsonwebtoken');
const { User } = require('../db/models');
const SECRET = 'TOKEN_SECRET';

const auth = async (req,res,next) => {
	const raw = req?.headers?.authorization?.split(' ')?.pop();
	if(!raw){
		return res.status(422).send({ success:false,message:'无token!' });
	}
	jwt.verify(raw,SECRET,async (err,decoded) => {
		if(!err){
			const { id } = decoded;
			req.userInfo = await User.findById(id);
			next();
		}else{
			return res.status(422).send({ success:false,message:'token 验证失败' });
		}
	});
};

module.exports = { auth };
